package com.zgc.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zgc.dto.OrderDto;
import com.zgc.entity.OrderDetail;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AliPayUtil {
    @Value("${zfb.web.appid}")
    private String appid;
    @Value("${zfb.web.serverUrl}")
    private String serverUrl;
    @Value("${zfb.web.primaryKey}")
    private String primaryKey;
    @Value("${zfb.web.alipayPublicKey}")
    private String alipayPublicKey;
    @Value("${zfb.web.format}")
    private String format;
    @Value("${zfb.web.charset}")
    private String charset;
    @Value("${zfb.web.signType}")
    private String signType;
    @Value("${zfb.web.callback}")
    private String callback;
    /**
     * 获取客户端
     * */
    public AlipayClient getClent(){
        AlipayClient alipayClient = new
                DefaultAlipayClient(serverUrl,appid,primaryKey,format,charset,alipayPublicKey,signType);
        return alipayClient;
    }
    /**
     * 获取支付请求对象
     * */
    public AlipayTradePagePayRequest getPayRequest(OrderDto orderDto){
        AlipayTradePagePayRequest request = new
                AlipayTradePagePayRequest();
//同步跳转地址，仅支持http/https http://localhost:8080/pay/check
        request.setReturnUrl(callback);
/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderDto.getId());
//支付金额，最小值0.01元
        bizContent.put("total_amount",orderDto.getAmount().toString());
//订单标题，不可使用特殊符号
        bizContent.put("subject", orderDto.getNumber());
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
/******可选参数******/
//bizContent.put("time_expire", "2022-08-01 22:00:00");
//// 商品明细信息，按需传入
        JSONArray goodsDetail = new JSONArray();
        for (OrderDetail orderDetail:orderDto.getOrderDetails()) {
            JSONObject goods1 = new JSONObject();
            goods1.put("goods_id", orderDetail.getId());
            goods1.put("goods_name", orderDetail.getName());
            goods1.put("quantity", orderDetail.getNumber());
            goods1.put("price", orderDetail.getAmount());
            goodsDetail.add(goods1);
        }
        bizContent.put("goods_detail", goodsDetail);
        request.setBizContent(bizContent.toString());
        return request;
    }
}

